import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../core/natives/natives.dart';
import '../../core/storage/local_storage.dart';
import '../model/user_info.dart';
import '../model/user_model.dart';

/// 用户共享数据
class UserProvider extends ChangeNotifier {
  UserProvider._();

  static final shared = UserProvider._();

  UserInfo? userInfo;
  UserOrderInfo? orderInfo;
  StoreInfo? storeInfo;

  /// 判断当前是否登录状态
  bool get isLogin => LocalStorage.token?.isNotEmpty ?? false;

  bool get isNotLogin => !isLogin;

  static int get userId => shared.userInfo?.userId ?? 0;

  static UserProvider of(BuildContext context) => context.read<UserProvider>();

  /// 更新用户信息。
  /// [UserModel] 相关的 json 数据，包含：userInfo、storeInfo、orderInfo
  void updateData(Map<String, dynamic> json) {
    _updateData(json);
    notifyListeners();
    _cacheData(json);
  }

  void updateUserInfo(UserInfo userInfo) {
    this.userInfo = userInfo;

    final model = UserModel()
      ..userInfo = userInfo
      ..orderInfo = orderInfo
      ..storeInfo = storeInfo;

    notifyListeners();
    _cacheData(model.toJson());
  }

  /// 退出登录，清空数据
  Future<void> logout() async {
    final uid = userId;

    userInfo = null;
    orderInfo = null;
    storeInfo = null;

    Natives.userLogout(uid: uid);

    /// 清空 token 缓存
    await LocalStorage.setUserToken(null);
    await _cacheData(<String, dynamic>{});

    notifyListeners();
  }

  void _updateData(Map<String, dynamic> json) {
    final userModel = UserModel.fromJson(json);
    if (userModel == null) {
      return;
    }

    userInfo = userModel.userInfo;
    orderInfo = userModel.orderInfo;
    storeInfo = userModel.storeInfo;
  }

  /// 本地缓存用户信息。
  Future<void> _cacheData(Map<String, dynamic> json){
    return Future.value();
  }


  /// 用户信息文件名
  late String userInfoFileName = 'UserInfo';

  /// 用户信息加密密钥
  String get userInfoSecretKey => 'TzVW4EmySYQVniKEiTsgoKUcKfLWmWKL';
}
